//
//  SchoolMapViewController.swift
//  HoneyBee
//
//  Created by point on 2018/2/10.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit

class SchollMapVCHeaderView: UIView {
    var backBtn = UIButton.init()
    var textField = UITextField.init()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(backBtn)
        addSubview(textField)
        backBtn.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.centerY.equalTo(self.snp.centerY)
            make.width.equalTo(40)
            make.height.equalTo((44))
        }
        textField.snp.makeConstraints { (make) in
            make.left.equalTo(backBtn.snp.right).offset(5)
            make.right.equalTo(self.snp.right).offset(-10)
            make.centerY.equalTo(self)
            make.height.equalTo(44)
        }
        textField.placeholder = "搜索机构名称"
        backBtn.backgroundColor = UIColor.white
        textField.backgroundColor = UIColor.white
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}




class SchoolMapViewController: BaseViewController{
    
    var mapView: BMKMapView?
    var modelArr:[SchoolModel] = [SchoolModel]()
    lazy var locService = BMKLocationManager()
    var userLocation:BMKUserLocation = BMKUserLocation()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        mapView?.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        mapView?.delegate = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "地图展现"
        view.backgroundColor = UIColor.white
        mapView = BMKMapView(frame: CGRect(x: 0, y: LayoutCommon.navHeight, width: self.view.frame.width, height: self.view.frame.height - LayoutCommon.navHeight))
        self.view.addSubview(mapView!)
        mapView?.isZoomEnabled = true //支持缩放
        mapView?.zoomLevel = 18
        postion()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        showAnnotation()
    }
}


// MARK: - 添加大头定位
extension SchoolMapViewController {
    func showAnnotation() {
        for model in modelArr {
            let annotation = BMKPointAnnotation()
            guard let latitude = Double(model.latitude) else {continue}
            guard let longitude = Double(model.longitude) else {continue}
            annotation.coordinate = CLLocationCoordinate2DMake(latitude,longitude)
            annotation.title = model.name
            mapView?.addAnnotation(annotation)
        }
    }
}


//MARK:- 地图代理
extension SchoolMapViewController:  BMKMapViewDelegate  , BMKLocationManagerDelegate {
    
    func bmkLocationManager(_ manager: BMKLocationManager, didUpdate heading: CLHeading?) {
        mapView?.updateLocationData(userLocation)
    }
    
    func bmkLocationManager(_ manager: BMKLocationManager, didUpdate location: BMKLocation?, orError error: Error?) {
        self.userLocation.location = location!.location
        
        mapView!.centerCoordinate =  self.userLocation.location.coordinate;
        mapView?.updateLocationData(userLocation)
        locService.stopUpdatingLocation()
    }
    
    func postion()  {
        locService.delegate = self
        locService.coordinateType = BMKLocationCoordinateType.BMK09LL
        locService.desiredAccuracy = kCLLocationAccuracyBest
        locService.activityType = CLActivityType.automotiveNavigation
        locService.pausesLocationUpdatesAutomatically = false
        locService.allowsBackgroundLocationUpdates = false
        locService.locationTimeout = 10
        locService.reGeocodeTimeout = 10
        locService.startUpdatingLocation()
        locService.locatingWithReGeocode = true
        mapView?.showsUserLocation = true
        mapView?.userTrackingMode = BMKUserTrackingModeNone
    }
}



extension SchoolMapViewController {

    func mapView(_ mapView: BMKMapView!, annotationViewForBubble view: BMKAnnotationView!) {
        var nodeArr = [BNRoutePlanNode]()
        
        let startNode = BNRoutePlanNode()
        startNode.pos = BNPosition()
        startNode.pos.x = userLocation.location.coordinate.longitude
        startNode.pos.y = userLocation.location.coordinate.latitude
        startNode.pos.eType = BNCoordinate_BaiduMapSDK
        nodeArr.append(startNode)
        
        
        
        let endNode = BNRoutePlanNode()
        endNode.pos = BNPosition()
        endNode.pos.x = view.annotation.coordinate.longitude
        endNode.pos.y = view.annotation.coordinate.latitude
        endNode.pos.eType = BNCoordinate_BaiduMapSDK
        nodeArr.append(endNode)
        
        let navVC = SchoolMapOCViewController()
        navVC.nodesArray = nodeArr
        self.navigationController?.pushViewController(navVC, animated: true)
    }
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        let newAnonotationView = BMKPinAnnotationView.init(annotation: annotation, reuseIdentifier: "annotation");
        
        newAnonotationView?.image = UIImage(named: "location")
        return newAnonotationView;
//        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        

    }
}
//
//    func routePlanDidFailedWithError(_ error: Error!, andUserInfo userInfo: [AnyHashable : Any]! = [:]) {
//        print("xxxx",error,userInfo)
//    }
//
//    func routePlanDidFinished(userInfo: [NSObject : AnyObject]!) {
//
//
//        let alertController = UIAlertController(title: "系统提示",
//                                                message: "导航需要您安装百度地图", preferredStyle: .alert)
//        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
//            action in
//            // BNCoreServices.uiService().showPage(BNaviUI_NormalNavi, delegate: nil, extParams: nil)
//        })
//        alertController.addAction(cancelAction)
//        alertController.addAction(okAction)
//        self.present(alertController, animated: true, completion: nil)
//    }
//}
//
//
//
//    //
//    //    func routePlanDidFinished(_ userInfo: [AnyHashable : Any]!) {
//    //        BNCoreServices.uiService().showPage(BNaviUI_NormalNavi, delegate: self
//    //            , extParams: nil)
//    //    }
//
//
//}

//        var nodeArr = [BNRoutePlanNode]()
//
//        let startNode = BNRoutePlanNode()
//        startNode.pos = BNPosition()
//        startNode.pos.x = currentLocation.coordinate.longitude
//        startNode.pos.y = currentLocation.coordinate.latitude
//        startNode.pos.eType = BNCoordinate_BaiduMapSDK
//        nodeArr.append(startNode)
//
//
//
//        let endNode = BNRoutePlanNode()
//        endNode.pos = BNPosition()
//        endNode.pos.x = view.annotation.coordinate.longitude
//        endNode.pos.y = view.annotation.coordinate.latitude
//        endNode.pos.eType = BNCoordinate_BaiduMapSDK
//        nodeArr.append(endNode)
//
//        let navVC = SchoolMapOCViewController()
//        navVC.nodesArray = nodeArr
//        self.navigationController?.pushViewController(navVC, animated: true)

//        baidunav.Begin_longitude = 113.977004  //初始点X 经度
//        baidunav.Begin_latitude = 22.556393  //初始点Y 纬度
//
//        baidunav.End_longitude = 114.089863   //终点X 经度
//        baidunav.End_latitude = 22.546236  //终点Y 纬度
//
//




//aa.refreshValidCode([])

//BNCoreServices.uiService().showPage(BNaviUI_NormalNavi, delegate: nil, extParams: nil)

//
//      //  BNCoreServices.routePlanService().startNaviRoutePlan(BNRoutePlanMode_Recommend, naviNodes: nodeArr, time: nil, delegete: self as! BNNaviRoutePlanDelegate   , userInfo: nil)
//       //Tool.xxx()
//        BNCoreServices.routePlanService().startNaviRoutePlan(BNRoutePlanMode_Recommend, naviNodes: nodeArr, time: nil, delegete: self, userInfo: nil)
//[nodesArray addObject:startNode];
/*
 //节点数组
 NSMutableArray *nodesArray = [[NSMutableArray alloc]    initWithCapacity:2];
 
 //起点
 
 
 //终点
 BNRoutePlanNode *endNode = [[BNRoutePlanNode alloc] init];
 endNode.pos = [[BNPosition alloc] init];
 endNode.pos.x = 114.077075;
 endNode.pos.y = 22.543634;
 endNode.pos.eType = BNCoordinate_BaiduMapSDK;
 [nodesArray addObject:endNode];
 //发起路径规划
 [BNCoreServices_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Recommend naviNodes:nodesArray time:nil delegete:self userInfo:nil];
 */
